package com.chenyue.cm.user.service.impl;


import java.io.Serializable;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.chenyue.cm.base.service.BaseServiceImpl;
import com.chenyue.cm.base.dao.LcBaseMapper;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.Constants;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.domain.JdDiscountCoupon;
import com.chenyue.cm.user.service.JdAppUserService;
import com.chenyue.cm.user.service.JdDiscountCouponService;
import com.chenyue.cm.utils.DateUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import com.chenyue.cm.user.dao.JdMemberCouponsMapper;
import com.chenyue.cm.user.domain.JdMemberCoupons;
import com.chenyue.cm.user.service.JdMemberCouponsService;
import org.springframework.stereotype.Service;


/**
*
* @author chenyue-cm
*/
@Service(value = "JdMemberCouponsService")
public class JdMemberCouponsServiceImpl extends BaseServiceImpl<JdMemberCoupons>  implements JdMemberCouponsService {

private final JdMemberCouponsMapper jdMemberCouponsMapper;
@Resource
private JdAppUserService appUserService;
@Resource
private JdDiscountCouponService discountCouponService;

	public JdMemberCouponsServiceImpl(@Qualifier("jdMemberCouponsMapper") JdMemberCouponsMapper jdMemberCouponsMapper) {
		this.jdMemberCouponsMapper = jdMemberCouponsMapper;
	}

	@Override
	@Resource(name = "jdMemberCouponsMapper")
	public void setBaseMapper(LcBaseMapper<JdMemberCoupons, Serializable> baseMapper) {
		this.baseMapper = baseMapper;
	}

	@Override
	public Success saveCoupons(HttpServletRequest request) {
		//根据token获取用户id
		JdAppUser appUser = appUserService.getAppUserByToken(request.getParameter("token"));
		if(appUser == null){
			return Success.error();
		}
		String couponsId = request.getParameter("couponsId");
		//用户领取优惠券校验
		Success r =checkInfo(appUser.getId().toString(),couponsId);
		if(r.getCode()!=0){
			return r;
		}
		saveInfo(appUser.getId().toString(),couponsId);
		return Success.success("领取成功");
	}

	@Override
	public Success checkCoupons(String userId, String couponsId, String orderId) {
        LambdaQueryWrapper<JdMemberCoupons> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdMemberCoupons::getMemberId,userId).eq(JdMemberCoupons::getCouponsId,couponsId).eq(JdMemberCoupons::getStatus,0);
        JdMemberCoupons mMemberCoupons = this.getOne(wrapper);
        if(mMemberCoupons==null){
            return Success.error("优惠券不可用");
        }
        //修改优惠券状态为已使用
        mMemberCoupons.setStatus(Constants.MEMBER_COUPONS_STATUS_1);
        this.updateById(mMemberCoupons);
        return Success.success();
	}

	@Override
	public Success cancelCoupons(String userId, String couponsId) {
        LambdaQueryWrapper<JdMemberCoupons> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JdMemberCoupons::getMemberId,userId).eq(JdMemberCoupons::getCouponsId,couponsId);
        JdMemberCoupons mMemberCoupons = this.getOne(wrapper);
        if(mMemberCoupons==null){
            return Success.error("优惠券不存在");
        }
        if(!mMemberCoupons.getStatus().equals(Constants.MEMBER_COUPONS_STATUS_2)){
            mMemberCoupons.setStatus(Constants.MEMBER_COUPONS_STATUS_0);
            this.updateByPrimaryKey(mMemberCoupons);
        }
        return Success.success();
	}

    /**
     * 保存用户优惠券信息
     * @param memberId
     * @param couponsId
     */
    public void saveInfo(String memberId, String couponsId) {
        //减库存
        JdDiscountCoupon mDiscountCoupon = discountCouponService.getById(couponsId);
        mDiscountCoupon.setRemainNum(mDiscountCoupon.getRemainNum()-1);
        discountCouponService.updateByPrimaryKey(mDiscountCoupon);
        JdMemberCoupons coupons = new JdMemberCoupons();
        coupons.setId(java.util.UUID.randomUUID().toString().replace("-", ""));
        coupons.setCouponsId(couponsId);
        coupons.setMemberId(memberId);
        coupons.setGetTime(DateUtils.getCurrentTime());
        coupons.setStatus(Constants.MEMBER_COUPONS_STATUS_0);
        coupons.setCt(DateUtils.getCurrentTime());
        coupons.setEt(DateUtils.getCurrentTime());
        this.save(coupons);
    }

	/**
	 * 1 校验优惠券是否已经领完
	 * 2.校验用户是否已经领过此券
	 * 3.优惠券建库存
	 * @return
	 */
	private Success checkInfo(String memberId, String couponsId) {
		//校验优惠券是否已经领完
        LambdaQueryWrapper<JdMemberCoupons> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(JdMemberCoupons::getMemberId,memberId).eq(JdMemberCoupons::getCouponsId,couponsId);
		int count = this.count(wrapper);
		if(count>0){
			return Success.error("请勿重复领取");
		}
		//校验优惠券是否已经领完
		JdDiscountCoupon mDiscountCoupon = discountCouponService.getById(couponsId);
		if(mDiscountCoupon.getRemainNum()<=0){
			return Success.error("优惠券已经领完");
		}

		return Success.success();
	}
}
